package zhuyun.code

import java.lang.Runnable

fun main(args:Array<String>){
    val context = ThreadContext()
    context.start()
    context.getCPU()
    context.suspend()
    context.resume()
    context.getCPU()
    context.stop()
}
abstract class ThreadState{
    protected lateinit var stateName:String
}
class New: ThreadState() {
    init {
        stateName = "新建状态"
        println("当前线程处于：新建状态.");
    }
    fun start(hj:ThreadContext){
        println("调用start方法")
        if("新建状态".equals(stateName)){
            hj.state = zhuyun.code.Runnable()
        } else {
            println("当前状态不是新建状态，不能调用start方法")
        }
    }
}
class Runnable:ThreadState(){
    init {
        stateName = "就绪状态"
        println("当前线程处于：就绪状态.");
    }
    fun getCPU(hj:ThreadContext){
        println("调用getCPU方法")
        if("就绪状态".equals(stateName)) {
            hj.state = Running()
        } else {
            println("当前状态不是就绪状态，不能调用getCPU方法")
        }
    }
}
class Running:ThreadState(){
    init {
        stateName = "运行状态"
        println("当前线程处于：运行状态.");
    }
    fun stop(hj:ThreadContext){
        println("调用stop方法")
        if("运行状态".equals(stateName)) {
            hj.state = zhuyun.code.Runnable()
        } else {
            println("当前状态不是运行状态，不能调用stop方法")
        }
    }
    fun suspend(hj:ThreadContext){
        println("调用suspend方法")
        if("运行状态".equals(stateName)) {
            hj.state = Blocked()
        } else {
            println("当前状态不是运行状态，不能调用suspend方法")
        }
    }
}

class Blocked:ThreadState(){
    init {
        stateName = "阻塞状态"
        println("当前线程处于：阻塞状态.");
    }
    fun resume(hj:ThreadContext){
        println("调用resume方法")
        if("阻塞状态".equals(stateName)) {
            hj.state = zhuyun.code.Runnable()
        } else {
            println("当前状态不是阻塞状态，不能调用resume方法")
        }
    }

}
class Dead:ThreadState(){
    init {
        stateName = "死亡状态"
        println("当前线程处于：死亡状态.");
    }
}


class ThreadContext{
    var state:ThreadState = New()
    fun start(){
        (state as New).start(this)
    }
    fun getCPU(){
        (state as zhuyun.code.Runnable).getCPU(this)
    }
    fun stop(){
        (state as Running).stop(this)
    }
    fun suspend(){
        (state as Running).suspend(this)
    }
    fun resume(){
        (state as Blocked).resume(this)
    }



}